<template>
  <div class="admin-dashboard">
    <h2>系统管理仪表盘</h2>
    
    <div v-if="loading && !stats.totalUsers" class="loading-container">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载中...</div>
    </div>
    <div v-else-if="error" class="error-message">{{ error }}</div>
    <div v-else>
      <div class="stats-overview">
        <div class="stat-card">
          <div class="stat-icon users-icon"></div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.totalUsers }}</div>
            <div class="stat-label">总用户数</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon statisticians-icon"></div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.totalStatisticians }}</div>
            <div class="stat-label">统计员数</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon records-icon"></div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.totalRecords }}</div>
            <div class="stat-label">健康记录数</div>
          </div>
        </div>
        
        <div class="stat-card abnormal-card">
          <div class="stat-icon abnormal-icon"></div>
          <div class="stat-content">
            <div class="stat-number abnormal-number">{{ stats.abnormalIndicators }}</div>
            <div class="stat-label">异常指标数</div>
          </div>
        </div>
      </div>
      
      <div class="dashboard-sections">
        <!-- 最近公告 -->
        <div class="section-card">
          <div class="section-header">
            <h3>最近公告</h3>
          </div>
          <div class="notices-list">
            <div v-for="notice in recentNotices" :key="notice.noticeId" class="notice-item">
              <div class="notice-title">{{ notice.title }}</div>
              <div class="notice-time">{{ formatTime(notice.createTime) }}</div>
              <div class="notice-content">{{ truncateText(notice.content, 50) }}</div>
            </div>
            <div v-if="recentNotices.length === 0" class="empty-notices">暂无公告记录</div>
          </div>
        </div>
        
        <!-- 快速操作 -->
        <div class="section-card quick-actions">
          <h3>快速操作</h3>
          <div class="actions-grid">
            <router-link to="/admin/user-management" class="action-card">
              <div class="action-icon user-manage-icon">👥</div>
              <div class="action-text">用户管理</div>
            </router-link>
            <router-link to="/admin/statistician-management" class="action-card">
              <div class="action-icon indicator-icon">📊</div>
              <div class="action-text">疾控中心统计员管理</div>
            </router-link>
            <router-link to="/admin/system-config" class="action-card">
              <div class="action-icon config-icon">⚙️</div>
              <div class="action-text">系统配置</div>
            </router-link>
            <a href="https://mail.163.com/" target="_blank" class="action-card">
              <div class="action-icon email-icon">✉️</div>
              <div class="action-text">我的邮箱</div>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import api from '@/utils/axiosConfig'

export default {
  name: 'AdminDashboard',
  setup() {
    const stats = reactive({
      totalUsers: 0,
      totalStatisticians: 0,
      totalRecords: 0,
      abnormalIndicators: 0
    })
    
    const recentNotices = ref([])
    const loading = ref(false)
    const error = ref('')
    
    // 获取仪表盘统计数据
    const fetchDashboardData = async () => {
      loading.value = true
      error.value = ''
      try {
        // 获取总用户数
        const userResponse = await api.get('/user/list')
        stats.totalUsers = userResponse.data.length
        
        // 获取统计员数(假设用户类型2为统计员)
        const statisticiansResponse = await api.get('/user/page', {
          params: { userType: 2, pageSize: 1 }
        })
        stats.totalStatisticians = statisticiansResponse.data.total
        
        // 获取健康记录总数
        const recordsResponse = await api.get('/health-indicator/getAll')
        stats.totalRecords = recordsResponse.data.length
        
        // 获取异常指标数
        const abnormalResponse = await api.get('/health-indicator/getAbnormalIndicators')
        stats.abnormalIndicators = abnormalResponse.data.length
      } catch (err) {
        console.error('获取仪表盘数据失败:', err)
        error.value = '获取数据失败，请稍后重试'
      } finally {
        loading.value = false
      }
    }
    
    // 获取最近公告
    const fetchRecentNotices = async () => {
      try {
        const response = await api.get('/sysNotice/getAll')
        // 取最近3条并按时间排序
        recentNotices.value = response.data
          .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
          .slice(0, 3)
      } catch (err) {
        console.error('获取最近公告失败:', err)
      }
    }
    
    // 格式化时间
    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return date.toLocaleString()
    }
    
    // 截断文本
    const truncateText = (text, length) => {
      if (!text) return ''
      return text.length > length ? text.substring(0, length) + '...' : text
    }
    
    // 页面加载时获取必要的数据
    onMounted(async () => {
      await Promise.all([
        fetchDashboardData(),
        fetchRecentNotices()
      ])
    })
    
    return {
      stats,
      recentNotices,
      loading,
      error,
      formatTime,
      truncateText
    }
  }
}
</script>

<style scoped>
.admin-dashboard {
  background-color: #fff;
  border-radius: 8px;
  padding: 24px;
  min-height: calc(100vh - 48px);
  box-sizing: border-box;
}

.admin-dashboard h2 {
  color: #1f2937;
  margin-bottom: 24px;
  font-size: 22px;
  font-weight: 600;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 5px solid #f0f5ff;
  border-top: 5px solid #409eff;
  border-radius: 50%;
  animation: spin 1.2s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: #409eff;
  font-size: 18px;
  font-weight: 500;
}

.error-message {
  text-align: center;
  padding: 40px;
  color: #ff4d4f;
  background-color: #fff2f0;
  border-radius: 8px;
  margin: 20px 0;
  border: 1px solid #ffccc7;
}

.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  height: 100%;
  box-sizing: border-box;
}

.stat-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26px;
}

.users-icon {
  background-color: #e6f7ff;
  color: #1890ff;
}

.statisticians-icon {
  background-color: #f6ffed;
  color: #52c41a;
}

.records-icon {
  background-color: #fff7e6;
  color: #fa8c16;
}

.abnormal-icon {
  background-color: #fee2e2;
  color: #ef4444;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #1f2937;
  line-height: 1.2;
}

.stat-label {
  color: #6b7280;
  font-size: 16px;
  margin-top: 4px;
}

/* 异常指标特殊样式 */
.stat-card.abnormal-card {
  border: 1px solid #fee2e2;
}

.stat-number.abnormal-number {
  color: #ef4444;
}

.dashboard-sections {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.section-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  box-sizing: border-box;
}

.quick-actions {
  border: none;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #606266;
  font-size: 16px;
  margin: 0;
  font-weight: 600;
}

.notices-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.notice-item {
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  border-left: 4px solid transparent;
  transition: all 0.2s ease;
  cursor: pointer;
  border: 1px solid #f2f3f5;
}

.notice-item:hover {
  border-left-color: #409eff;
  background-color: #f9fafc;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

.notice-title {
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 6px;
  font-size: 16px;
}

.notice-time {
  color: #9ca3af;
  font-size: 13px;
  margin-bottom: 8px;
}

.notice-content {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.empty-notices {
  text-align: center;
  padding: 40px 20px;
  color: #9ca3af;
  font-size: 15px;
  background-color: #f9fafc;
  border-radius: 8px;
  border: 1px dashed #e5e7eb;
}

.empty-notices::before {
  content: "📄";
  font-size: 24px;
  display: block;
  margin-bottom: 8px;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.action-card {
  padding: 24px 16px;
  background-color: #f9fafc;
  border-radius: 12px;
  text-decoration: none;
  transition: all 0.3s ease;
  border: 1px solid #f2f3f5;
}

.action-card:hover {
  background-color: #ecf5ff;
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  border-color: #c6e2ff;
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-bottom: 12px;
}

.user-manage-icon { color: #409eff; }
.indicator-icon { color: #fa8c16; }
.config-icon { 
  background-color: #409eff;
  color: #fff; 
}
.email-icon { 
  background-color: #67c23a;
  color: #fff; 
}

.action-text {
  color: #303133;
  font-weight: 500;
  font-size: 15px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .dashboard-sections {
    grid-template-columns: 1fr;
  }
  
  .stats-overview {
    grid-template-columns: 1fr 1fr;
  }
}

@media (max-width: 480px) {
  .stats-overview {
    grid-template-columns: 1fr;
  }
  
  .actions-grid {
    grid-template-columns: 1fr;
  }
  
  .admin-dashboard {
    padding: 16px;
  }
}
</style>